package com.ciaojian.client.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ciaojian.client.service.OrderCommentServiceImpl;
import com.ciaojian.client.service.OrderCommissionServiceImpl;
import com.ciaojian.client.service.OrderServiceImpl;
import com.ciaojian.client.service.UserServiceImpl;
import com.ciaojian.core.base.annotation.ApiIdempotent;
import com.ciaojian.core.enums.business.OrderStatusEnum;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.model.OrderComment;
import com.ciaojian.core.model.User;
import com.ciaojian.core.model.vo.CommentVo;
import com.ciaojian.core.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @author Atlakyn
 */
@Slf4j
@Api(tags = "服务评价")
@RestController
@RequestMapping("/order/comment")
public class OrderCommentController {

    @Resource
    private OrderCommentServiceImpl orderCommentService;
    @Resource
    private OrderServiceImpl orderService;
    @Resource
    private UserServiceImpl userService;
    @Resource
    private OrderCommissionServiceImpl orderCommissionService;

    @ApiOperation("展示服务评价列表")
    @GetMapping("/comment-list")
    public Result commentList(Integer id) {
        // 按评价时间降序排列（score为4/5）
        QueryWrapper<OrderComment> wrapper;
        // 总评论数
        wrapper = new QueryWrapper<>();
        wrapper.eq("store_id", id).select("count(1) as score");
        OrderComment total = orderCommentService.getOne(wrapper);

        // 好评率：好评数[满意/非常满意]/评价总数
        String goodRate = orderCommentService.goodRate(id, total.getScore());

        HashMap<String, Object> map = new HashMap<>(3);
        map.put("goodRate", goodRate);
        map.put("total", total.getScore());
        return Result.ok(map);
    }

    /**
     * 服务评价详情页
     */
    @ApiOperation("服务评价详情页")
    @GetMapping("/comment-list-detail")
    public Result commentListDetail(Integer userId,
                                    Integer storeId,
                                    Integer type,
                                    Integer workerId,
                                    @RequestParam(value = "page", defaultValue = "0") Integer pageNo,
                                    @RequestParam(value = "size", defaultValue = "6") Integer pageSize) {
        /*
         * 1.累积评论统计
         */
        CommentVo commentVo = orderCommentService.getBaseMapper().countCommentByWorkerIdAndStoreId(userId, workerId, storeId);

        Page<OrderComment> page = orderCommentService.page(userId, storeId, type, workerId, pageNo, pageSize);

        if (page.getTotal() != 0) {
            // 将 img 值中的"["和"]"剔除
            for (OrderComment record : page.getRecords()) {
                String img = record.getImg();
                if (img != null) {
                    String s1 = img.replace("[", "");
                    String s2 = s1.replace("]", "");
                    record.setImg(s2);
                }
            }
        }

        HashMap<String, Object> map = new HashMap<>(2);
        map.put("Census", commentVo);
        map.put("typeComment", page);
        return Result.ok(map);
    }

    /**
     * 添加评价
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiIdempotent
    @PutMapping
    public Result addComment(@RequestBody OrderComment orderComment) {
        // 校验此笔订单是否评价过
        Assert.isTrue(orderCommentService.notCommented(orderComment.getOrderId()), "该订单已评价");

        Integer orderId = orderComment.getOrderId();
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("id", orderId);
        Order order = orderService.getOne(wrapper);

        //三个月前时间不能评价
        Date nowDate = new Date();
        Assert.isTrue(nowDate.getTime()-order.getAddTime().getTime()<7689600000L,"三个月前的订单无法评价");

        Assert.isTrue(order.getStatus().equals(OrderStatusEnum.paid), "网络延迟,请稍后再试");

        orderComment.setStoreId(order.getStoreId());
        orderComment.setWorkerId(order.getWorkerId());
        orderComment.setWorkerName(order.getWorkerName());
        orderComment.setUserId(order.getUserId());
        orderComment.setType(order.getType());
        orderComment.setIsDefault(0);

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = dateFormat.format(date);
        orderComment.setAddTime(addTime);


        User user = userService.getById(order.getUserId());
        if(ObjectUtil.isNotNull(order.getChannel())){
            if (order.getChannel()==2){
                if (ObjectUtil.isNotNull(user.getDyNickName())) {
                    orderComment.setUserNickname(user.getDyNickName());
                } else {
                    orderComment.setUserNickname("抖音用户");
                }

                if (ObjectUtil.isNotNull(user.getDyAvatarUrl())) {
                    orderComment.setUserAvatar(user.getDyAvatarUrl());
                } else {
                    orderComment.setUserAvatar("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
                }
                orderComment.setChannelType(2);
            }
            if (order.getChannel()==1){
                if (ObjectUtil.isNotNull(user.getNickName())) {
                    orderComment.setUserNickname(user.getNickName());
                } else {
                    orderComment.setUserNickname("微信用户");
                }

                if (ObjectUtil.isNotNull(user.getAvatarUrl())) {
                    orderComment.setUserAvatar(user.getAvatarUrl());
                } else {
                    orderComment.setUserAvatar("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
                }
                orderComment.setChannelType(1);
            }
        }else {
            if (ObjectUtil.isNotNull(user.getNickName())) {
                orderComment.setUserNickname(user.getNickName());
            } else {
                orderComment.setUserNickname("微信用户");
            }

            if (ObjectUtil.isNotNull(user.getAvatarUrl())) {
                orderComment.setUserAvatar(user.getAvatarUrl());
            } else {
                orderComment.setUserAvatar("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
            }
            orderComment.setChannelType(1);
        }

        orderComment.setAutoComment(0);

        try {
            orderCommentService.save(orderComment);
            // 评分后新增提成记录
            orderCommissionService.insertAfterComment(orderComment);

            log.info(">>>addComment,orderComment={}>>>", orderComment);
            order.setStatus(OrderStatusEnum.complete);
            order.updateById();
            return Result.ok("评价成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("评价失败!");
        }
    }
}

